import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { Http, Response, Headers, RequestOptions } from '@angular/http';

/**
 * 获取客户端数据
 */
@Injectable()
export class GlobalData {
    public config: any;
    constructor(
        private http: Http
    ) {
    }


    public httpPost(url: string, postData: any, callback: Function): void {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        this.http.post(url, postData, options)
            .map(this.extractData)
            .catch(this.handleError).subscribe({
                next: body => callback(body),
                error: err => this.handleError(err),
                complete: () => { },
            });
    }

    private extractData(res: Response) {
        let body = res.json() || {};
        return body || {};
    }

    private handleError(error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }
}